<?php
/**
 * Created by PhpStorm.
 * User: 86158
 * Date: 2021/6/14
 * Time: 12:12
 */

namespace App\Models\user;

use App\Models\exams\Exam;
use App\Models\Model;
use App\Models\news\News;
use App\Models\User;
use function foo\func;

class Collect extends Model
{
    protected $fillable = [
        'user_id',
        'resource_id',
        'type',
        'status'
    ];

    public function user()
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    public function news()
    {
        return $this->hasOne(News::class,'id','resource_id');
    }

    public function exams()
    {
        return $this->hasOne(Exam::class,'id','resource_id');
    }

    /**
     * 添加收藏记录
     * @param $data
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function add($data)
    {
        return self::firstOrCreate($data);
    }

    /**
     * 获取用户收藏列表
     * @param $user_id
     * @return array
     */
    public static function collectList($user_id,$type = 1,$pageSize = 10)
    {
        $map['user_id'] = $user_id;
        $map['type'] = $type;
        $map['status'] = 1;
        $data = self::where($map)
            ->when($type == 1,function ($query){
                $query->with('news');
            })
            ->when($type == 2,function ($query){
                $query->with('exams');
            })
            ->select(['user_id','resource_id','status','type'])
            ->paginate($pageSize);
        return $data;
    }

    /**
     * 更新收藏状态
     * @param $map
     * @param $status
     * @return int
     */
    public function modify($map,$status)
    {
        return self::where($map)->update(['status'=>$status]);
    }

    /**
     * 收藏和取消收藏
     * @param $type
     * @param $user_id
     * @param $resource_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     */
    public function collect($type,$user_id,$resource_id)
    {
        $map = [
            'type' => $type,
            'user_id' => $user_id,
            'resource_id' => $resource_id,
        ];
        $data = self::where($map)->first();
        if($data){
            $status = $data['status'] == 1 ? 0 : 1;
            self::where($map)->update(['status'=>$status]);
        }else{
            $map['status'] = 1;
            $data = self::firstOrCreate($map);
        }
        return $data;
    }
}